package com.zhiwang.planet.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.view.WindowManager
import android.webkit.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat.checkSelfPermission
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.planet.R
import com.zhiwang.planet.aop.net.NetWorkRequired
import com.zhiwang.planet.ui.jsmodule.*
import com.zhiwang.planet.ui.my.VipRecordActivity
import com.zhiwang.planet.ui.webview_ultimate.Interceptor
import com.zhiwang.planet.ui.webview_ultimate.WebViewInterceptorHelper
import com.zhiwang.planet.util.*
import kotlinx.android.synthetic.main.activity_web_view.*


class WebViewActivity : BaseActivity(), WebViewPageHandler {

    companion object {

        @NetWorkRequired
        fun load(context: Context, url: String) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            if (url == Store.URL_MEMBER_SHIP || url == Store.URL_LOTTERY)
                intent.putExtra("KEY_IMMERSIVE", true)
            context.startActivity(intent)
        }


        @NetWorkRequired
        fun load(context: Context, url: String, needTitle: Boolean) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            intent.putExtra("KEY_TITLE", needTitle)
            context.startActivity(intent)
        }


        @NetWorkRequired
        fun loadImmersive(context: Context, url: String) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            intent.putExtra("KEY_IMMERSIVE", true)
            context.startActivity(intent)
        }

        fun loadImmersiveWithNav(context: Context, url: String) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            intent.putExtra("KEY_IMMERSIVE", true)
            intent.putExtra("KEY_NAV", true)
            context.startActivity(intent)
        }
    }

    private val PHOTO_PICK_REQUEST_CODE: Int = 114

    private val REQUEST_PERMISSION_WRITE_STORAGE: Int = 113

    var filePathCallback: ValueCallback<Array<Uri>>? = null


    val TAG = "WebViewActivity"


    //初始url
    private lateinit var url: String
    private var needTitle: Boolean = true
    private var needImmersive = false

    //保存每次页面跳转之后的url
    private lateinit var currUrl: String
    private lateinit var appName: String

    fun getAjaxString() = "javascript:" +
            "\$.ajaxSetup({\n" +
            "            headers: {\n" +
            "                \"appdevice\": \'android\',\n" +
            "                \"apptoken\": \'${getAppToken()}\'\n" +
            "            }\n" +
            "        });\n"

    fun getAppToken() = TokenManager.token()


    private lateinit var interceptor: Interceptor

    private fun albumIntent(): Intent {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        return intent
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_web_view)
        interceptor = WebViewInterceptorHelper.get()
        configWebViewSetting()
        receiveKeys()
        setUpUi()
    }


    private fun receiveKeys() {
        url = intent.getStringExtra("KEY_URL")
        needTitle = intent.getBooleanExtra("KEY_TITLE", true)
        needImmersive = intent.getBooleanExtra("KEY_IMMERSIVE", false)
        currUrl = url
    }


    private fun setUpUi() {

        Utils.setStatusBar(this, true, false)
        Utils.setStatusTextColor(true, this)

        if (!needTitle)
            toolbar.visibility = View.GONE

        if (needImmersive) {
            toolbar.setGone()
            Utils.setStatusBar(this, true, false)
            val lp = window.attributes
            //针对水滴屏（刘海屏）的全屏处理
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
            }
        }

        if (url == Store.URL_MEMBER_SHIP || url == Store.URL_VIP_CENTER) {
            vip_layout.setVisible()
            if (url == Store.URL_VIP_CENTER)
                vip_toolbar.title = ""
            setSupportActionBar(vip_toolbar)
        } else setSupportActionBar(toolbar)

        supportActionBar!!.setDisplayHomeAsUpEnabled(true)

        interceptor.initLoad(masterWebView.webView!!, url)
//        masterWebView.webView?.loadUrl(url, webViewHeader())

        if (url == Store.URL_PC28) {
            swipeRefreshLayout.setEnableRefresh(false)
        }

        swipeRefreshLayout.setOnRefreshListener {
            refresh()
        }
    }

    fun refresh() {
        runOnUiThread {
            swipeRefreshLayout.autoRefresh()
            masterWebView.webView?.loadUrl(url, webViewHeader())
        }
    }

    fun loadUrl() {
        masterWebView?.webView?.loadUrl(url, webViewHeader())
    }

    override fun onSupportNavigateUp(): Boolean {
        onBack()
        return true
    }


    override fun onDestroy() {
        super.onDestroy()
        interceptor.onDestroy()
        masterWebView?.removeAllViews()
        masterWebView?.webView?.destroy()
    }

    override fun onBackPressed() {
        onBack()
    }

    private fun onBack() {

        interceptor.onGoBack(this, masterWebView.webView as WebView)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == PHOTO_PICK_REQUEST_CODE && data != null) {
            filePathCallback?.onReceiveValue(arrayOf(data.data))
            return
        }
        filePathCallback?.onReceiveValue(null)
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == REQUEST_PERMISSION_WRITE_STORAGE && grantResults[0] == PERMISSION_GRANTED)
            startActivityForResult(albumIntent(), PHOTO_PICK_REQUEST_CODE)
    }


    fun vipRecord(view: View) {
        quickStartActivity(VipRecordActivity::class.java)
    }

    override fun onResume() {
        super.onResume()
        interceptor.onResume(masterWebView.webView!!)
    }

    private fun installJsModules() {

        val android = JsInjector
                .Builder()
                .addAppUsageModule(AppUsageModule(this, ::loadUrl))
                .addCommonModule(CommonModule(this, masterWebView?.webView))
                .addMembershipModule(MembershipModule(this))
                .addRefreshJsModule(RefreshJsModule(this, swipeRefreshLayout, ::loadUrl))
                .addNavJsModule(NavJsModule(this))
                .addShareModule(ShareModule(this))
                .addSdkModule(SdkModule(this))
                .create()

        //直接编译生成所有的
        masterWebView.webView?.addJavascriptInterface(android, "android")
    }

    @SuppressLint("SetJavaScriptEnabled")
    fun configWebViewSetting() {

        val settings = masterWebView.webView?.settings
        settings?.javaScriptEnabled = true
        settings?.useWideViewPort = true
        settings?.domStorageEnabled = true
        settings?.loadWithOverviewMode = true
        settings?.cacheMode = WebSettings.LOAD_NO_CACHE
        settings?.setSupportZoom(true)
        settings?.builtInZoomControls = true
        settings?.displayZoomControls = true
        settings?.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        settings?.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        masterWebView.webView?.webViewClient = webViewClient
        val webChromeClient: WebChromeClient = webChromeClient
        masterWebView.webView?.webChromeClient = webChromeClient
        installJsModules()
        CrashReport.setJavascriptMonitor(masterWebView.webView, true)
    }

    private val webViewClient: WebViewClient = object : WebViewClient() {

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            interceptor.onPageStart(view)
        }

        override fun onPageFinished(view: WebView, url: String?) {
            val ajaxString = getAjaxString()
            view.loadUrl(ajaxString)
//            toolbar.title = view.title.toString()
            swipeRefreshLayout.finishRefresh()
            interceptor.onPageFinish(view)
        }

        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {

            val r  =  interceptor.shouldInterceptUrlLoading(view,request.url.toString())
            if (r)return  r
            else return  super.shouldOverrideUrlLoading(view, request)
        }


    }

    private val webChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            interceptor.onPageProgress(view, newProgress)

        }

        override fun onReceivedTitle(view: WebView?, title: String?) {
            super.onReceivedTitle(view, title)
            toolbar.title = title
        }

        override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>?, fileChooserParams: FileChooserParams?): Boolean {

            this@WebViewActivity.filePathCallback = filePathCallback
            if (checkSelfPermission(this@WebViewActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PERMISSION_GRANTED) {
                startActivityForResult(albumIntent(), PHOTO_PICK_REQUEST_CODE)
            } else {
                ActivityCompat.requestPermissions(this@WebViewActivity,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        REQUEST_PERMISSION_WRITE_STORAGE)
            }
            return true

        }

        override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {

            return interceptor.onConsoleMessage(masterWebView!!.webView as WebView, consoleMessage)
        }


    }

    override fun closePage() {
        suicideAfterTransition()
    }

    override fun setRefreshEnabled(enable: Boolean) {
        swipeRefreshLayout.setEnableRefresh(enable)
    }

    override fun setRefreshing(refreshing: Boolean) {
        if (refreshing)
            swipeRefreshLayout.autoRefresh()
        else swipeRefreshLayout.finishRefresh()
    }


}


open interface WebViewPageHandler {

    fun closePage()

    fun setRefreshEnabled(enable: Boolean)

    fun setRefreshing(refreshing: Boolean)
}